package com.yangl.study.context;

import com.yangl.study.beans.BeanDefinition;
import com.yangl.study.beans.factory.AbstractBeanFactory;
import com.yangl.study.beans.factory.AutowireCapableBeanFactory;
import com.yangl.study.beans.io.ResourceLoader;
import com.yangl.study.beans.xml.XmlBeanDefinitionReader;

import java.util.Map;

/**
 * @author yanglei
 * @date 2021-12-05 21:45
 */
public class ClassPathXmlApplicationContext extends AbstractApplicationContext {

    private String configLocation;

    /**
     * 通过配置文件实例化 ClassPathXmlApplicationContext
     * @param configLocation 配置文件路径
     * @throws Exception 异常
     */
    public ClassPathXmlApplicationContext(String configLocation) throws Exception {
        // 实例化 AutowireCapableBeanFactory , 构建初始缓存集合对象
        this(configLocation, new AutowireCapableBeanFactory());
    }

    public ClassPathXmlApplicationContext(String configLocation, AbstractBeanFactory beanFactory) throws Exception {
        // 实例化 AbstractApplicationContext 并设置 beanFactory
        super(beanFactory);
        // 设置 configLocation 配置文件路径
        this.configLocation = configLocation;
        // 刷新 beanFactory
        refresh();
    }

    @Override
    protected void loadBeanDefinitions(AbstractBeanFactory beanFactory) throws Exception {
        XmlBeanDefinitionReader xmlBeanDefinitionReader = new XmlBeanDefinitionReader(new ResourceLoader());
        xmlBeanDefinitionReader.loadBeanDefinitions(configLocation);
        for (Map.Entry<String, BeanDefinition> beanDefinitionEntry : xmlBeanDefinitionReader.getRegistry().entrySet()) {
            beanFactory.registerBeanDefinition(beanDefinitionEntry.getKey(), beanDefinitionEntry.getValue());
        }
    }

}
